package com.bd.controller;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.context.RequestContext;

import com.bd.model.CD;
import com.bd.util.StringUtil;

@Named("cdBean")
@ViewScoped
public class CDBean {

	@Inject
	private ControllerImpl	controller;

	private List<CD>		myCds;

	public List<CD> findAllCDs() {
		if (myCds == null)
			return controller.findAllCDs();
		else
			return myCds;
	}

	public void clearFilters() {
		myCds = null;
		RequestContext fc = RequestContext.getCurrentInstance();
		// fc.reset(":panel");
	}

	public void removeCD(CD cd) {
		try {
			controller.removeCD(cd);
			FacesContext.getCurrentInstance().addMessage("Removido com sucesso!",
							new FacesMessage(FacesMessage.SEVERITY_INFO, "Removido com sucesso", "Removido com sucesso!"));
		} catch (Throwable e) {
			StringUtil.addErrorMessage("Erro ao tentar remover", cd.getId() + "");
		}
	}

	public void saveCD(CD cd) {
		FacesContext context = FacesContext.getCurrentInstance();

		try {
			controller.saveCD(cd);
			context.addMessage(null, new FacesMessage("Sucesso!", "CD salvo com sucesso!"));
		} catch (Exception e) {
			e.printStackTrace();
			context.addMessage(null, new FacesMessage("Erro ao salvar", "Ocorreu um erro ao tentar salvar o CD"));
		}
	}

	public void findCDByExample(CD cd) {
		if (cd.getId() == 0 && cd.getDescricao().isEmpty() && cd.getPreco() == null && cd.getDataCompra() == null && cd.getDataGravacao() == null)
			myCds = null;
		else
			myCds = controller.findCDByExample(cd);
	}

}
